# Contributor: Antoine Martin (ayakael) <dev@ayakael.net>
# Maintainer: Antoine Martin (ayakael) <dev@ayakael.net>
pkgname=py3-django-pgactivity
#_pkgreal is used by apkbuild-pypi to find modules at PyPI
_pkgreal=django-pgactivity
pkgver=1.6.0
pkgrel=0
pkgdesc="View, filter, and kill Postgres queries."
url="https://pypi.python.org/project/django-pgactivity"
arch="noarch"
license="BDS-3-Clause"
depends="
	py3-django
	py3-importlib-metadata
	"
checkdepends="
	procps-ng
	py3-dj-database-url
	py3-django-dynamic-fixture
	py3-django-extensions
	py3-psycopg2
	py3-pytest
	py3-pytest-cov
	py3-pytest-django
	py3-pytest-mock
	py3-pytest-reraise
	py3-typing-extensions
	postgresql
	"
makedepends="
	py3-setuptools
	py3-gpep517
	py3-wheel
	poetry
	"
source="$pkgname-$pkgver.tar.gz::https://github.com/Opus10/django-pgactivity/archive/refs/tags/$pkgver.tar.gz"
builddir="$srcdir/$_pkgreal-$pkgver"
subpackages="$pkgname-pyc"

prepare() {
	default_prepare

	# For some reason importlib.metadata can't find package metadata:
	#   importlib.metadata.PackageNotFoundError: No package metadata was found for django-pgactivity
	echo "__version__ = \"$pkgver\"" > "$builddir"/version.py
	echo "__version__ = \"$pkgver\"" > "$builddir"/pgactivity/version.py
}

build() {
	gpep517 build-wheel \
		--wheel-dir .dist \
		--output-fd 3 3>&1 >&2
}

check() {
	msg "Setting up test environment"
	export POSTGRES_DB=pglock_local
	export POSTGRES_USER=postgres
	export POSTGRES_PASSWORD="postgres"
	export DATABASE_URL="postgres://$POSTGRES_USER@localhost:5432/$POSTGRES_DB"

	rm -Rf "$srcdir"/tmp
	initdb -D "$srcdir"/tmp
	postgres -D "$srcdir"/tmp --unix-socket-directories="$srcdir" > "$srcdir"/tmp/psql.log 2>&1 &

	trap "pkill postgres" EXIT
	# wait for psql to be ready
	while ! pg_isready -h "$srcdir" > /dev/null 2>&1; do
		sleep 0.5
	done
	psql -h "$srcdir" -d postgres -c "CREATE ROLE $POSTGRES_USER PASSWORD '$POSTGRES_PASSWORD' INHERIT LOGIN;"
	psql -h "$srcdir" -d postgres -c "CREATE DATABASE $POSTGRES_DB OWNER $POSTGRES_USER ENCODING 'UTF-8';"
	psql -h "$srcdir" -d postgres -c "ALTER USER $POSTGRES_USER WITH SUPERUSER;"

	python3 -m venv --clear --without-pip --system-site-packages .testenv
	.testenv/bin/python3 -m installer .dist/*.whl

	msg "Running tests"
	.testenv/bin/python3 -m pytest -v

	pkill postgres

	# wait for postgres death
	sleep 5
	rm -rf "$srcdir"/tmp
}

package() {
	python3 -m installer -d "$pkgdir" \
		.dist/*.whl
}

sha512sums="
89d38808cd9f473e6a23ef88463c6d3915081b5a31c6460cbb20003e08306b3e6c74707280dc0fb49a02a1e33ac5ef8af8eadbb0bc0e42718cf566c0054266e8  py3-django-pgactivity-1.6.0.tar.gz
"
